package cn.xu.framework.common.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author Clark Xu<clark2021@qq.com>
 * @date 2024/8/2
 */
public class FileUtil {

    public static void main(String[] args) {
//        split1();
//        split2();
        split3();
//        findDuplicateFiles();

//        // 获取源文件路径
//        Path sourcePath = Paths.get("D:\\work\\tmp\\场景分类-09", "1.txt");
//        System.out.println(sourcePath.toAbsolutePath().toString());
    }

    private static void split3() {
        String parentPath = "D:\\work\\tmp\\LabelmeData_v8";
        String path1 = "D:\\work\\tmp\\场景分类-08(4)_xuxiaoyu";
        String path2 = "D:\\work\\tmp\\场景分类-08(4)_xiongkun";
        String path3 = "D:\\work\\tmp\\场景分类-08(4)_tanxiang";
        File pf = new File(parentPath);
        File[] files = pf.listFiles();
        System.out.println(files.length);
        int total = files.length;
        int first = total/3;
        System.out.println(first);

        for(int i = 0;i<total;i++){
            File file = files[i];
//            System.out.println(file.getName());
            if(i<=first){
                moveFile(parentPath, path1, file.getName());
            }else if(i<=(first+first)){
                moveFile(parentPath, path2, file.getName());
            }else{
                moveFile(parentPath, path3, file.getName());
            }
        }
    }
    private static void split2() {
        String parentPath = "D:\\work\\tmp\\zheng_09_label_0801_xu";
        String path1 = "D:\\work\\tmp\\zheng_09_label_0801_xuxiaoyu";
        String path2 = "D:\\work\\tmp\\zheng_09_label_0801_xiongkun";
        String path3 = "D:\\work\\tmp\\zheng_09_label_0801_xgf";
        File pf = new File(parentPath);
        File[] files = pf.listFiles();
        System.out.println(files.length);
        int total = files.length;
        int first = total/3;
        System.out.println(first);

        for(int i = 0;i<total;i++){
            File file = files[i];
//            System.out.println(file.getName());
            if(i<=first){
                moveFile(parentPath, path1, file.getName());
            }else if(i<=(first+first)){
                moveFile(parentPath, path2, file.getName());
            }else{
                moveFile(parentPath, path3, file.getName());
            }
        }
    }
    private static void split1() {
        String parentPath = "D:\\work\\tmp\\zheng_09_label_0801";
        String path1 = "D:\\work\\tmp\\zheng_09_label_0801_tan";
        String path2 = "D:\\work\\tmp\\zheng_09_label_0801_xu";
        File pf = new File(parentPath);
        File[] files = pf.listFiles();
        System.out.println(files.length);
        int total = files.length;
        int first = total/3;
        System.out.println(first);

        for(int i = 0;i<total;i++){
            File file = files[i];
//            System.out.println(file.getName());
            if(i<=first){
                moveFile(parentPath, path1, file.getName());
            }else{
                moveFile(parentPath, path2, file.getName());
            }
        }
    }

    public static void moveFile(String sourceFolder, String targetFolder, String fileName) {
        try {
            // 获取源文件路径
            Path sourcePath = Paths.get(sourceFolder, fileName);

            // 获取目标文件路径
            Path targetPath = Paths.get(targetFolder, fileName);
            // 创建目标文件夹，如果它不存在
            Files.createDirectories(targetPath.getParent());

            // 移动文件
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void findDuplicateFiles(){
        String directoryPath = "D:\\work\\tmp\\zheng_09_label_0801_xu"; // 替换为你的文件夹路径
        Map<String, List<Path>> filesByMd5 = findDuplicateFiles(directoryPath);

        // 输出具有相同MD5值的文件
        filesByMd5.entrySet().stream()
                .filter(entry -> entry.getValue().size() > 1)
                .forEach(entry -> {
                    System.out.println("MD5: " + entry.getKey());
                    entry.getValue().forEach(path -> System.out.println("\t" + path));
                });
    }

    private static Map<String, List<Path>> findDuplicateFiles(String directoryPath) {
        Map<String, List<Path>> filesByMd5 = new HashMap<>();

        try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
            paths.filter(Files::isRegularFile)
                    .forEach(path -> {
                        try {
                            String md5 = calculateMd5(path);
                            filesByMd5.computeIfAbsent(md5, k -> new ArrayList<>()).add(path);
                        } catch (IOException e) {
                            System.err.println("Error reading file: " + path);
                        }
                    });
        } catch (IOException e) {
            System.err.println("Error walking directory: " + e.getMessage());
        }

        return filesByMd5;
    }

    private static String calculateMd5(Path path) throws IOException {
        try (InputStream is = Files.newInputStream(path)) {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int read;

            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }

            byte[] hash = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String readStr(File file) {
        InputStream read = null;
        String context = null;
        try {
            read = Files.newInputStream(file.toPath());
            byte[] bt = new byte[read.available()];
            read.read(bt);
            context = new String(bt, StandardCharsets.UTF_8);
            read.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (read != null) {
                try {
                    read.close(); //确保关闭
                } catch (IOException el) {
                }
            }
        }
        return context;
    }

    public static String readLineStr(File file, String... ignorePrefixs) {
        InputStream read = null;
        String context = null;
        BufferedReader br = null;
        try {
            read = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(read));
            String str = null;
            StringBuffer sb = new StringBuffer();
            while((str = br.readLine()) != null) {
                if(ignorePrefixs!=null&&ignorePrefixs.length>0){
                    boolean ignore = false;
                    for(String prefix: ignorePrefixs){
                        if(str.trim().startsWith(prefix)){
                            ignore = true;
                            break;
                        }
                    }
                    if(ignore){
                        continue;
                    }
                }
                sb.append(str);
                sb.append("\n");
            }
            context = sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close(); //确保关闭
                } catch (IOException el) {
                }
            }
            if (read != null) {
                try {
                    read.close(); //确保关闭
                } catch (IOException el) {
                }
            }
        }
        return context;
    }

//    public static void writeStr(String str, String url) throws IOException {
//        OutputStreamWriter out = new OutputStreamWriter(Files.newOutputStream(Paths.get(url)), StandardCharsets.UTF_8);
//        out.write(str);
//        out.close();
//    }

    public static void writeStr(String str, String url) throws IOException {
        Path path = Paths.get(url);
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            writer.write(str);
        }
    }
}
